<template>
  <div class="location-management-container">
    <header class="location-header">
      <h2>药店管理</h2>
      <button class="add-btn" @click="openAddDialog">新增药店</button>
    </header>
    
    <!-- 消息提示 -->
    <div v-if="message" class="message" :class="{ 'success': messageType === 'success', 'error': messageType === 'error' }">
      {{ message }}
    </div>
    
    <div class="filter-bar">
      <input v-model="filter.name" placeholder="药店名称" class="filter-input" />
      <input v-model="filter.phone" placeholder="药店电话" class="filter-input" />
      <input v-model="filter.address" placeholder="药店地址" class="filter-input" />
      <button class="filter-btn" @click="applyFilter">查询</button>
      <button class="filter-btn" @click="resetFilter">重置</button>
    </div>
    <div class="location-table-scroll">
      <table class="location-table">
        <thead>
          <tr>
            <th>药店名称</th>
            <th>药店电话</th>
            <th>药店地址</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="location in pagedLocations" :key="location.id">
            <td>{{ location.name }}</td>
            <td>{{ location.phone }}</td>
            <td>{{ location.address }}</td>
            <td>
              <button @click="openEditDialog(location)">编辑</button>
              <button @click="deleteLocation(location.id)">删除</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="pagination">
      <button :disabled="page===1" @click="page--">上一页</button>
      <span>第 {{ page }} 页 / 共 {{ totalPages }} 页</span>
      <button :disabled="page===totalPages" @click="page++">下一页</button>
    </div>

    <!-- 新增/编辑弹窗 -->
    <div v-if="showDialog" class="dialog-mask">
      <div class="dialog location-dialog">
        <h3 class="dialog-title">{{ editMode ? '编辑药店' : '新增药店' }}</h3>
        <form @submit.prevent="saveLocation">
          <label class="dialog-label">药店名称：<input v-model="form.name" required class="dialog-input" /></label>
          <label class="dialog-label">药店电话：<input v-model="form.phone" required pattern="^1[3-9]\d{9}$" type="text" class="dialog-input" /></label>
          <label class="dialog-label">药店地址：<input v-model="form.address" required class="dialog-input" /></label>
          <div class="dialog-actions">
            <button type="submit" :disabled="loading" class="dialog-btn primary">{{ loading ? '保存中...' : '保存' }}</button>
            <button type="button" @click="closeDialog" class="dialog-btn cancel">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import axios from 'axios';

const locations = ref([]);
const loading = ref(false);
const message = ref('');
const messageType = ref('');

const filter = ref({ name: '', phone: '', address: '' });
const filteredLocations = computed(() => {
  return locations.value.filter(l => {
    return (
      (!filter.value.name || l.name.includes(filter.value.name)) &&
      (!filter.value.phone || l.phone.includes(filter.value.phone)) &&
      (!filter.value.address || l.address.includes(filter.value.address))
    );
  });
});
const page = ref(1);
const pageSize = 10;
const totalPages = computed(() => Math.ceil(filteredLocations.value.length / pageSize));
const pagedLocations = computed(() => {
  const start = (page.value - 1) * pageSize;
  return filteredLocations.value.slice(start, start + pageSize);
});

const showDialog = ref(false);
const editMode = ref(false);
const form = ref({ id: null, name: '', phone: '', address: '' });

// 显示消息提示
function showMessage(msg, type = 'success') {
  message.value = msg;
  messageType.value = type;
  setTimeout(() => {
    message.value = '';
    messageType.value = '';
  }, 3000);
}

// 获取所有药店
async function fetchLocations() {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.get('http://47.93.134.56:8800/pharmacy/get/all', {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      locations.value = response.data.data || [];
    } else {
      showMessage(response.data.msg || '获取药店列表失败', 'error');
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
  } finally {
    loading.value = false;
  }
}

// 添加药店
async function addLocation(locationData) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/pharmacy/add', locationData, {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '添加药店成功');
      await fetchLocations(); // 重新获取列表
      return true;
    } else {
      showMessage(response.data.msg || '添加药店失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

// 更新药店
async function updateLocation(locationData) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.post('http://47.93.134.56:8800/pharmacy/update', locationData, {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '更新药店成功');
      await fetchLocations(); // 重新获取列表
      return true;
    } else {
      showMessage(response.data.msg || '更新药店失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

// 删除药店
async function deleteLocationById(id) {
  try {
    loading.value = true;
    const storedToken = localStorage.getItem('token');
    const response = await axios.delete(`http://47.93.134.56:8800/pharmacy/delete/${id}`, {
      headers: {
        'token': storedToken
      }
    });
    if (response.data.code === 200) {
      showMessage(response.data.msg || '删除药店成功');
      await fetchLocations(); // 重新获取列表
      return true;
    } else {
      showMessage(response.data.msg || '删除药店失败', 'error');
      return false;
    }
  } catch (error) {
    showMessage(error.response?.data?.msg || '网络错误', 'error');
    return false;
  } finally {
    loading.value = false;
  }
}

function openAddDialog() {
  editMode.value = false;
  form.value = { id: null, name: '', phone: '', address: '' };
  showDialog.value = true;
}

function openEditDialog(location) {
  editMode.value = true;
  form.value = { ...location };
  showDialog.value = true;
}

function closeDialog() {
  showDialog.value = false;
}

async function saveLocation() {
  if (!form.value.name || !form.value.phone || !form.value.address) {
    showMessage('请填写完整信息', 'error');
    return;
  }
  
  let success = false;
  if (editMode.value) {
    success = await updateLocation(form.value);
  } else {
    success = await addLocation(form.value);
  }
  
  if (success) {
    showDialog.value = false;
  }
}

async function deleteLocation(id) {
  if (confirm('确定要删除该药店吗？')) {
    await deleteLocationById(id);
  }
}

function applyFilter() {
  page.value = 1;
}

function resetFilter() {
  filter.value = { name: '', phone: '', address: '' };
  page.value = 1;
}

// 页面加载时获取数据
onMounted(() => {
  fetchLocations();
});
</script>

<style scoped>
.location-management-container {
  background: #fff;
  border-radius: 10px;
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  overflow: hidden;
}

/* 消息提示样式 */
.message {
  padding: 12px 16px;
  margin-bottom: 15px;
  border-radius: 6px;
  font-size: 0.9rem;
  font-weight: 500;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

.location-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.add-btn {
  background: #3498db;
  color: #fff;
  border: none;
  padding: 8px 18px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1rem;
}
.add-btn:hover {
  background: #217dbb;
}
.filter-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 18px;
  align-items: center;
}
.filter-input {
  padding: 6px 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
}
.filter-btn {
  background: #3498db;
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}
.filter-btn:hover {
  background: #217dbb;
}
.location-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}
.location-table th, .location-table td {
  border: 1px solid #e0e0e0;
  padding: 10px 8px;
  text-align: center;
}
.location-table th {
  background: #f4f7f9;
}
.location-table tr:nth-child(even) {
  background: #fafbfc;
}
.location-table button {
  margin: 0 4px;
  padding: 4px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.95rem;
  transition: all 0.3s ease;
}
.location-table button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 删除按钮样式 */
.location-table button:last-child {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
.location-table button:last-child:hover {
  background-color: #f5c6cb;
  color: #721c24;
}

/* 编辑按钮样式 */
.location-table button:first-child {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}
.location-table button:first-child:hover {
  background-color: #c3e6cb;
  color: #155724;
}

/* 添加按钮样式 */
.add-btn {
  background-color: #007bff !important;
  color: white !important;
}
.add-btn:hover {
  background-color: #0056b3 !important;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 16px;
  justify-content: flex-end;
}
.dialog-mask {
  position: fixed;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.18);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.location-dialog {
  background: white;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  animation: slideIn 0.3s ease;
  border: 1px solid #e0e0e0;
  padding: 30px 28px 18px 28px;
}
@keyframes slideIn {
  from { opacity: 0; transform: translateY(-50px) scale(0.95); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
.dialog-title {
  margin: 0 0 25px 0;
  font-size: 1.4rem;
  font-weight: 600;
  color: #2c3e50;
  text-align: center;
  padding-bottom: 15px;
  border-bottom: 2px solid #3498db;
}
.location-dialog form {
  padding: 0 20px 20px 20px;
}
.dialog-label {
  display: block;
  margin-bottom: 18px;
  font-size: 1rem;
  font-weight: 500;
  color: #34495e;
}
.dialog-input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background: #fafbfc;
}
.dialog-input:focus {
  outline: none;
  border-color: #3498db;
  background: white;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}
.dialog-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #e0e0e0;
}
.dialog-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}
.dialog-btn.primary {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  box-shadow: 0 4px 15px rgba(52, 152, 219, 0.3);
}
.dialog-btn.primary:hover {
  background: linear-gradient(135deg, #2980b9, #1f5f8b);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(52, 152, 219, 0.4);
}
.dialog-btn.cancel {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
  color: white;
  box-shadow: 0 4px 15px rgba(149, 165, 166, 0.3);
}
.dialog-btn.cancel:hover {
  background: linear-gradient(135deg, #7f8c8d, #6c7b7d);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(149, 165, 166, 0.4);
}
@media (max-width: 600px) {
  .location-dialog {
    padding: 18px 6vw 12px 6vw;
    min-width: 0;
    max-width: 98vw;
  }
  .dialog-title {
    font-size: 1.1rem;
  }
  .dialog-btn {
    padding: 8px 12px;
    font-size: 0.95rem;
    min-width: 70px;
  }
}
.location-management-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.location-table-scroll {
  flex: 1 1 auto;
  min-height: 0;
  max-height: none;
  overflow-y: auto;
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
}
.location-table thead th {
  position: sticky;
  top: 0;
  z-index: 2;
  background: #f4f7f9;
}
.location-table-scroll::-webkit-scrollbar {
  width: 8px;
  background: #f4f7f9;
  border-radius: 8px;
}
.location-table-scroll::-webkit-scrollbar-thumb {
  background: #dbeafe;
  border-radius: 8px;
}
.location-table-scroll:hover::-webkit-scrollbar-thumb {
  background: #b6d4fe;
}
</style>